package com.imchen.cms.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author imchen
 * @create: 2019-01-29 17:40
 **/
public class IntArrayTypeHandler extends BaseTypeHandler<int[]> {

    private Logger logger = LoggerFactory.getLogger(IntArrayTypeHandler.class);

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, int[] integers, JdbcType jdbcType) throws SQLException {
        logger.debug("i:{} array:{} jdbcType:{}",i,integers,jdbcType);
        List<String> list =new ArrayList<>();
        for (int item : integers){
            list.add(String.valueOf(item));
        }
        preparedStatement.setString(i,String.join(",",list));
    }

    @Override
    public int[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        logger.debug("resultSet;{} s:{}",resultSet,columnName);
        String result= resultSet.getString(columnName);
        return toIntArray(result);
    }

    @Override
    public int[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        logger.debug("resultSet;{} i:{}",resultSet,i);
        String result= resultSet.getString(i);
        return toIntArray(result);
    }

    @Override
    public int[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        logger.debug("callableStatement:{} i:{}",callableStatement,i);
        String result=callableStatement.getString(i);
        return toIntArray(result);
    }

    private int[] toIntArray(String result){
        if (result.isEmpty()) {
            return null;
        }
        return Arrays.stream(result.split(",")).mapToInt(Integer::valueOf).toArray();
    }
}